from PySide6.QtCore import Qt, Slot ,QSize
from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout,
                               QStackedWidget, QToolButton, QButtonGroup,QSizePolicy,
                               QLabel, QStyle)
from PySide6.QtTextToSpeech import QTextToSpeech
from PySide6.QtSerialPort import QSerialPort
from PySide6.QtBluetooth import (QBluetoothDeviceDiscoveryAgent,
                                 QBluetoothSocket, QBluetoothLocalDevice,
                                 QBluetoothServiceInfo, QBluetoothUuid)
from PySide6.QtMultimedia import QAudioDevice, QMediaDevices, QAudioFormat
from chat_page import ChatPage
from me_page import MePage
import time


class MainWindow(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('微信风格应用')
        self.resize(400, 600)
        self.last_time = None

        # ---- 主布局 ----
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)

        # 堆栈窗口
        self.stacked = QStackedWidget()
        main_layout.addWidget(self.stacked)

        # 底栏
        self._create_tab_bar(main_layout)

    # 初始化 TTS
        self.setup_tts()

        self.serial = QSerialPort(self)
        self.local_bt = QBluetoothLocalDevice()
        self.discovery = QBluetoothDeviceDiscoveryAgent(self)
        self.bt_socket: QBluetoothSocket | None = None

        # ---- 页面 ----
        self.chat_page = ChatPage(self.discovery, self)
        self.contacts_page = QLabel('联系人页面\n（占位）', alignment=Qt.AlignCenter)
        self.chat_page.r_data_singal.connect(self.serial_text)
        self.discover_page = self._build_discover_page()
        self.me_page = MePage(self.serial, self)
        self.me_page.r_data_singal.connect(self.serial_text)

        for p in (self.chat_page, self.contacts_page,
                  self.discover_page, self.me_page):
            self.stacked.addWidget(p)

        # ---- 信号 ----
        # self.text_to_speech.stateChanged.connect(self._on_speech_state)
        self.serial.readyRead.connect(self.me_page.on_serial_read)
        self.bt_scan_done()  # 初始状态

    def serial_text(self, text):
        if self.last_time is None:
            self.last_time = time.time()
            
            self.tts_input.setText("当前" + text + "厘米")
            self._on_speak()
        else:
            if time.time() - self.last_time >= 2:
                self.tts_input.setText("当前" + text + "厘米")
                self.last_time = time.time()
                self._on_speak()
            
        
    def setup_tts(self):
        """设置文本转语音"""
        # 检查可用的引擎
        available_engines = QTextToSpeech.availableEngines()
        print("可用TTS引擎:", available_engines)
        

        
        if available_engines:
            if 'sapi' in available_engines:
                name = 'sapi'
            else:
                name = available_engines[0]
            # 尝试使用第一个可用引擎
            self.text_to_speech = QTextToSpeech(name, self)
        else:
            self.text_to_speech = QTextToSpeech(self)
        
        # 检查可用声音
        print("可用声音:")
        for voice in self.text_to_speech.availableVoices():
            print(f"  - {voice.name()}")
        
        # 设置合适的语音
        voices = self.text_to_speech.availableVoices()
        if voices:
            self.text_to_speech.setVoice(voices[0])  # 使用第一个可用声音
        
        # 设置音频格式（关键修复）
        self.set_audio_format()
        
        # 连接信号
        self.text_to_speech.stateChanged.connect(self._on_speech_state)

    def set_audio_format(self):
        """设置支持的音频格式"""
        device = QMediaDevices.defaultAudioOutput()
        if not device:
            # 使用设备推荐的格式
            preferred_format = device.preferredFormat()
            print(f"使用音频格式: {preferred_format.sampleRate()}Hz, {preferred_format.channelCount()}声道")
            
            # 设置音量、语速等参数
            self.text_to_speech.setVolume(1.0)
            self.text_to_speech.setRate(0.0)
            self.text_to_speech.setPitch(0.0)


    # ============ UI 构建 ============
    def _create_tab_bar(self, parent_layout):
        bar = QHBoxLayout()
        bar.setSpacing(0)
        bar.setContentsMargins(0, 0, 0, 0)

        self.btn_group = QButtonGroup(self)
        self.btn_group.setExclusive(True)
        self.btn_group.idClicked.connect(self.stacked.setCurrentIndex)

        texts = ['聊天', '联系人', '发现', '我']
        icons = [QStyle.SP_MessageBoxInformation,
                 QStyle.SP_FileDialogDetailedView,
                 QStyle.SP_FileDialogContentsView,
                 QStyle.SP_FileDialogListView]

        for idx, (txt, ico) in enumerate(zip(texts, icons)):
            btn = QToolButton()
            btn.setText(txt)
            btn.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
            btn.setIcon(self.style().standardIcon(ico))
            btn.setIconSize(QSize(24, 24))
            btn.setCheckable(True)
            btn.setSizePolicy(QSizePolicy.Expanding,
                              QSizePolicy.Preferred)
            bar.addWidget(btn)
            self.btn_group.addButton(btn, idx)
            if idx == 0:
                btn.setChecked(True)

        parent_layout.addLayout(bar)

    def _build_discover_page(self):
        from PySide6.QtWidgets import (QVBoxLayout, QLineEdit,
                                       QPushButton, QLabel)
        page = QWidget()
        lay = QVBoxLayout(page)
        lay.addWidget(QLabel('发现页面', alignment=Qt.AlignCenter))

        self.tts_input = QLineEdit(placeholderText='请输入要朗读的文字...')
        self.tts_btn = QPushButton('朗读')
        self.tts_status = QLabel('准备就绪', alignment=Qt.AlignCenter)
        lay.addWidget(self.tts_input)
        lay.addWidget(self.tts_btn)
        lay.addWidget(self.tts_status)
        lay.addStretch()
        page.setStyleSheet('background:#e8f8e8;')

        self.tts_btn.clicked.connect(self._on_speak)
        self.tts_input.returnPressed.connect(self._on_speak)
        return page

    # ============ 语音槽 ============
    @Slot()
    def _on_speak(self):
        txt = self.tts_input.text().strip()
        if not txt:
            self.tts_status.setText('请输入文字')
            return
        self.text_to_speech.say(txt)

    @Slot(QTextToSpeech.State)
    def _on_speech_state(self, st):
        if st == QTextToSpeech.State.Ready:
            self.tts_status.setText('朗读完成')
            self.tts_btn.setEnabled(True)
        elif st == QTextToSpeech.State.Speaking:
            self.tts_status.setText('正在朗读...')
            self.tts_btn.setEnabled(False)

    # ============ 蓝牙扫描结束 ============
    def bt_scan_done(self):
        self.chat_page.scan_btn.setEnabled(True)